package com.baizhi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCUtil {
    private static ThreadLocal<Connection> tl  = new ThreadLocal<Connection>();

    public static Connection getConnection() throws Exception{
        Connection conn = tl.get();
        if(conn == null){
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai","root","root");
            tl.set(conn);
        }
        return conn;
    }
    //关闭链接
    public static void close(Connection conn , PreparedStatement pstm , ResultSet rs){
        if(conn != null) try{ conn.close(); tl.remove();}catch(Exception e){}
        if(pstm != null) try{ pstm.close(); }catch(Exception e){}
        if(rs != null) try{ rs.close(); }catch(Exception e){}
    }
    //关闭链接
    public static void close(Connection conn ){
        if(conn != null) try{ conn.close(); tl.remove();}catch(Exception e){}
    }
    //关闭链接
    public static void close(PreparedStatement pstm){
        if(pstm != null) try{ pstm.close(); }catch(Exception e){}
    }
}
